package com.iwhalecloud.bss.kite.cucc.service.attr;

import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.cucc.client.dto.inf.req.QryDevloperReqDTO;
import com.ztesoft.common.logger.api.ZLogger;
import com.ztesoft.common.logger.factory.ZLoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageInfo;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.attr.ILocalQueryDevInfoService;
import com.iwhalecloud.bss.kite.cucc.client.api.inf.IInfServiceBus;
import com.iwhalecloud.bss.kite.cucc.client.dto.attr.ChannelKindDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.devInfo.response.QueryChannelInfoSerRsp;
import com.iwhalecloud.bss.kite.cucc.client.dto.devInfo.response.QueryDeveloperInfoRespDTO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalInfConsts;
import com.iwhalecloud.bss.kite.cucc.dataservice.cache.AreaNameCache;
import com.iwhalecloud.bss.kite.cucc.dataservice.cache.ChannelKindCache;
import com.iwhalecloud.bss.kite.cucc.service.util.LocalTokenUtil;
import com.ztesoft.bss.common.util.ContextUtil;

@Service
public class LocalQueryDevInfoService implements ILocalQueryDevInfoService {

    @Autowired
    private IInfServiceBus infServiceBus;

    @Override
    public List<ChannelKindDTO> queryDevInfoChanelType() {
        return ChannelKindCache.get("all");
    }

    private final ZLogger LOGGER = ZLoggerFactory.getLogger(this.getClass(), KeyConsts.LOG_MODULE);

    @Override
    public PageInfo<QueryChannelInfoSerRsp> queryDevInfoChanelInfo(String chnlCode, String chnlName, String chnlKindId, String pageSize, String pageNum) {
        Map<String, Object> qryChannelInfoReq = new HashMap<>();
        Map<String, Object> tcpCont = new HashMap<>();
        tcpCont.put("APP_KEY", LocalInfConsts.APP_ID);
        tcpCont.put("TRANSACION_ID", LocalTokenUtil.getTransId());
        qryChannelInfoReq.put("TCP_CONT", tcpCont);

        Map<String, Object> operUserInfo = new HashMap<>();
        operUserInfo.put("STAFF_ID", KiteStringUtils.valueOf(ContextUtil.getSimpleLoginInfo().getUserId()));
        operUserInfo.put("USER_CODE", ContextUtil.getSimpleLoginInfo().getUserCode());
        operUserInfo.put("USER_ORG_ID", KiteStringUtils.valueOf(ContextUtil.getSimpleLoginInfo().getOrgId()));
        qryChannelInfoReq.put("OPER_USER_INFO", operUserInfo);

        qryChannelInfoReq.put("CHNL_CODE", chnlCode);
        qryChannelInfoReq.put("CHNL_NAME", chnlName);
        qryChannelInfoReq.put("CHNL_KIND_ID", chnlKindId);
        //云业务49国际工号入参特殊处理
        String provinceCode = ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
        if(!KiteStringUtils.isEmpty(provinceCode)&&provinceCode.startsWith("49")){
            qryChannelInfoReq.put("PROVINCE_CODE", "09");
            if(KiteStringUtils.isEmpty(chnlKindId)){
                qryChannelInfoReq.put("CHNL_KIND_ID", "1020200");
            }
        }else {
            qryChannelInfoReq.put("PROVINCE_CODE", ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr());
            qryChannelInfoReq.put("EPARCHY_CODE", ContextUtil.getLoginInfo().getUserInfo().getPostLanId());
        }

        qryChannelInfoReq.put("PAGE_SIZE", pageSize);
        qryChannelInfoReq.put("PAGE_NUM", pageNum);


        return infServiceBus.qryChannelInfo(qryChannelInfoReq, Integer.valueOf(Optional.ofNullable(pageSize).orElse("10")), Integer.valueOf(Optional.ofNullable(pageNum).orElse("1")));
    }

    @Override
    public PageInfo<QueryDeveloperInfoRespDTO> queryDevInfoChanelStaff(QryDevloperReqDTO qryDevloperReqDTO) {
        String chnlCode = KiteStringUtils.isEmpty(qryDevloperReqDTO.getChnlCode())?null:qryDevloperReqDTO.getChnlCode();
        String devName = KiteStringUtils.isEmpty(qryDevloperReqDTO.getDevName())?null:qryDevloperReqDTO.getDevName();
        String devCode = KiteStringUtils.isEmpty(qryDevloperReqDTO.getDevCode())?null:qryDevloperReqDTO.getDevCode();
        String provinceCode  = KiteMapUtils.getString(qryDevloperReqDTO.getOperUserInfo(),"provinceCode");
        if(KiteStringUtils.isNotEmpty(KiteMapUtils.getString(qryDevloperReqDTO.getOperUserInfo(),"islocal"))){
            qryDevloperReqDTO.setOperUserInfo(null);
        }
        //provinceCode = KiteStringUtils.isEmpty(provinceCode)?ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr():provinceCode;
        String devPhone = KiteStringUtils.isEmpty(qryDevloperReqDTO.getDevPhone())?null:qryDevloperReqDTO.getDevPhone();
        Integer pageSize = qryDevloperReqDTO.getPageSize()==null?10:qryDevloperReqDTO.getPageSize();
        Integer pageNum = qryDevloperReqDTO.getPageNum()==null?1:qryDevloperReqDTO.getPageNum();
        Map userInfoParam = qryDevloperReqDTO.getOperUserInfo();
        Map<String, Object> qryDeveloperInfoReq = new HashMap<>();
        Map<String, Object> tcpCont = new HashMap<>();
//        tcpCont.put("APP_ID", LocalInfConsts.APP_ID);
        tcpCont.put("TRANSACION_ID", LocalTokenUtil.getTransId());
        qryDeveloperInfoReq.put("TCP_CONT", tcpCont);
        //极简调用取登录信息 二级研发取入参
        Map operUserInfo = new HashMap();
        if(KiteMapUtils.isEmpty(userInfoParam)){
            operUserInfo.put("STAFF_ID", KiteStringUtils.valueOf(ContextUtil.getSimpleLoginInfo().getUserId()));
            operUserInfo.put("USER_CODE", ContextUtil.getSimpleLoginInfo().getUserCode());
            operUserInfo.put("USER_ORG_ID", KiteStringUtils.valueOf(ContextUtil.getSimpleLoginInfo().getOrgId()));
        }else {
            operUserInfo.put("STAFF_ID", KiteMapUtils.getString(userInfoParam,"staffId"));
            operUserInfo.put("USER_CODE", KiteMapUtils.getString(userInfoParam,"userCode"));
            operUserInfo.put("USER_ORG_ID", KiteMapUtils.getString(userInfoParam,"userOrgId"));
        }
        qryDeveloperInfoReq.put("OPER_USER_INFO", operUserInfo);
        qryDeveloperInfoReq.put("CHNL_CODE", chnlCode);
        qryDeveloperInfoReq.put("DEV_NAME", devName);
        qryDeveloperInfoReq.put("DEV_CODE", devCode);
        qryDeveloperInfoReq.put("LINKMAN_PHONE", devPhone);
        //云业务，查发展人49工号不传省份编码
        if(KiteStringUtils.isNotEmpty(provinceCode)&&provinceCode.startsWith("49")){
            qryDeveloperInfoReq.put("PROVINCE_CODE", "09");
        }else {
            qryDeveloperInfoReq.put("PROVINCE_CODE", provinceCode);
        }

        qryDeveloperInfoReq.put("STATE", "10"); // 发展人状态  10-正常 12-删除
        qryDeveloperInfoReq.put("PAGE_SIZE", pageSize); // 每页显示条数 必填
        qryDeveloperInfoReq.put("PAGE_NUM", pageNum); // 第几页 必填

//        List<ChannelInfoParaDTO> paraList = new ArrayList<>();
//        qryDeveloperInfoReq.put("paraList", paraList);
        LOGGER.info(JSON.toJSONString(qryDeveloperInfoReq));
        return infServiceBus.qryDeveloperInfoSer(qryDeveloperInfoReq, pageSize, pageNum);
    }

    @Override
    public String queryAreaNameByCode(String provinveCode, String cityCode) {
        return AreaNameCache.get(provinveCode + "-" + cityCode);
    }

    @Override
    public DataResult<PageInfo<QueryDeveloperInfoRespDTO>> queryDevInfoChanelByKeyCode(QryDevloperReqDTO qryDevloperReqDTO) {
        try{
            String provinceCode = null;
            if(KiteMapUtils.isNotEmpty(qryDevloperReqDTO.getOperUserInfo())){
                provinceCode = KiteMapUtils.getString(qryDevloperReqDTO.getOperUserInfo(),"provinceCode");
            }
            PageInfo<QueryDeveloperInfoRespDTO> developers = this.queryDevInfoChanelStaff(qryDevloperReqDTO);
            if (!Objects.isNull(developers)&&!KiteListUtils.isEmpty(developers.getList())) {
                Set<String> chnlCodes = developers.getList().stream().map(dev->dev.getChnlCode()).collect(Collectors.toSet());
                Map chnlNames = infServiceBus.batchQueryDeveloChannelInfo(KiteStringUtils.join(chnlCodes.toArray(),","),provinceCode);
                developers.getList().stream().forEach(dev->{
                    Map chnlInfo = KiteMapUtils.getMap(chnlNames,dev.getChnlCode(),new HashMap());
                    dev.setChnlName(KiteMapUtils.getString(chnlInfo,"CHNL_NAME",""));
                });
            }else {
                return ErrorConsts.SUCCESS.getResult(new PageInfo<>(new ArrayList<>()));
            }
            return ErrorConsts.SUCCESS.getResult(developers);
        }catch (Exception e){
            LOGGER.error(ErrorConsts.SYSTEM_ERROR.getErrorCode(), e, e.getMessage());
            //return ErrorConsts.SYSTEM_ERROR.getResult(new PageInfo<>(new ArrayList<>()),e.getMessage());
            return new DataResult(ErrorConsts.SYSTEM_ERROR.getCode(),e.getMessage(),new PageInfo<>(new ArrayList<>()));
        }
    }
}
